package com.wchen.project.zk.demo;

import org.apache.zookeeper.*;
import org.apache.zookeeper.data.Stat;

import java.util.List;
import java.util.concurrent.CountDownLatch;

/**
 * @Desc:   zookeeper API 获取子节点列表，使用异步 sync 接口
 * @author: cww
 * @DateTime: 2020/1/17 20:02
 */

public class ZooKeeperGetChildrenASyncAPI implements Watcher {
    private static CountDownLatch connectedSemaphore = new CountDownLatch(1);
    private static ZooKeeper zk = null;

    public static void main(String[] args) throws Exception{
        String path = "/zk-book";
        zk = new ZooKeeper("home:2181", 5000, new ZooKeeperGetChildrenASyncAPI());
        connectedSemaphore.await();
        zk.delete(path,0);
        zk.create(path, "".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
        zk.create(path+"/c1", "".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL);
        zk.getChildren(path, true, new IChildren2Callback(), null);
        zk.create(path + "/c2", "".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL);
        Thread.sleep(5000);
    }
    @Override
    public void process(WatchedEvent event) {
        if (Event.KeeperState.SyncConnected == event.getState()) {
            if (Event.EventType.None == event.getType() && null == event.getPath()) {
                connectedSemaphore.countDown();
            } else if (event.getType() == Event.EventType.NodeChildrenChanged) {
                try {
                    System.out.println("ReGetChild: " + zk.getChildren(event.getPath(), true));
                } catch (KeeperException e) {
                    e.printStackTrace();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
class IChildren2Callback implements AsyncCallback.Children2Callback {

    /**
     * Process the result of the asynchronous call.
     * See {@link ChildrenCallback}.
     *
     * @param rc       The return code or the result of the call.
     * @param path     The path that we passed to asynchronous calls.
     * @param ctx      Whatever context object that we passed to
     *                 asynchronous calls.
     * @param children An unordered array of children of the node on
     *                 given path.
     * @param stat     {@link Stat} object of
     */
    @Override
    public void processResult(int rc, String path, Object ctx, List<String> children, Stat stat) {
        System.out.println("Get Children znode result: [response code: " + rc + ",param path: " + path
                + ",ctx: " + ctx + ",children list: " +children +",stat: " + stat);
    }
}